<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 车辆维保申请 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}">
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="车辆维保申请"></title-name>
          <custom-form :formList="formList" :form="form" :editModel="editModel == 0 ? 'V' : ''">
            <!-- 人员 -->
            <template #protectProject>
              <div class="custom-labelForm-s1">
                <a-checkbox-group v-model="form.protectProject" :options="options" v-if="editModel != 0"
                  style="width: 100%; display: flex; flex-wrap: wrap"></a-checkbox-group>
                <div v-else style="margin-top: -3px">{{ form.protectProject || '无' }}</div>
              </div>
            </template>
            <!-- 维保类型 -->
            <template #maintenanceTypes>
              <div class="custom-labelForm-s2">
                <a-checkbox-group v-model="form.maintenanceTypes" :options="options1"
                  style="width: 100%; display: flex; flex-wrap: wrap" :disabled="editModel == 0"></a-checkbox-group>
              </div>
            </template>
          </custom-form>
        </a-card>
        <a-card :bordered="false" v-if="editModel == 0 && form.realTime && statusCode == '2'">
          <title-name title="实际维保信息"></title-name>
          <custom-form :formList="maintenanceForm" :form="form" editModel="V">
            <!-- 人员 -->
            <template #fileInfoVOS>
              <file-link :fileList="form.fileInfoVOS" style="margin-top: -3px"></file-link>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top" v-if="!isAudit">
        <a-button style="margin-right: 10px; display: flex;align-items: center" :loading="printLoading" v-if="statusCode==2&&editModel==0">
          <BasePrintButton type="link" :innerSpinning="false"
                           @getLoadedState="getLoadedState"
                         :beforePrintFn="checkProjectRiskReturnPrint(id)" />
        </a-button>
        <a-button :loading="loading[0]" :disabled="loading[1]"
          v-if="(editModel == 1 && (statusCode == '0' || statusCode == '3')) || editModel == 2" type="primary"
          class="button_right" @click="handleSubmit(0)">{{ statusCode == '2' || statusCode == '3' ? '保存' : '保存草稿'
          }}</a-button>
        <a-button :loading="loading[1]" :disabled="loading[0]" v-if="
          (editModel == 1 && (statusCode == '0' || statusCode == '3')) ||
          editModel == 2 ||
          (editModel != 0 && statusCode == '2')
        " type="primary" class="button_right" @click="handleSubmit(1)">提交</a-button>
        <a-button v-if="checkVisibleInDetail" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { carMaintenanceApplication, carInfo } from '@/api/office/vehicle/config' // api
import { getDataDict } from '@/api/office/supervise.js'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import Selector from '@/components/Select/Selector'
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
export default {
  extends: new BaseEditPage(),
  components: {
    BasePrintButton
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      printLoading: false,
      loading: { 0: false, 1: false }, // 草稿和提交按钮loding
      visible: false, // 人员弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {}, // 表单
      statusCode: '', // 审批状态
      rules: {
        carNumber: [{ required: true, message: '请输入车牌号', trigger: 'change' }],
        preKilometre: [{ required: true, message: '请输入维保公里数（km）', trigger: 'change' }],
        budget: [{ required: true, message: '请输入预计总费用（元）', trigger: 'change' }],
        maintenanceTypes: [{ required: true, message: '请选择维保类型', trigger: 'change' }],
        protectProject: [{ type: 'array', required: true, message: '请选择维保项目', trigger: 'change' }],
        other: [{ required: true, whitespace: true, message: '请输入其他', trigger: 'change' }],
      }, // 校验规则
      options: [
        '检修发动机',
        '更换化油器',
        '检修变速器',
        '检修方向机',
        '更换减震器',
        '更换前/后轮轴承',
        '检修离合器总成',
        '检修发电机',
        '更换蓄电池',
        '检修全车线路',
        '检修空调系统及管道',
        '更换压缩机',
        '更换冷凝器',
        '检修节气门',
        '更换大/小灯泡',
        '检修刹车总/分泵',
        '检修刹车真空泵',
        '检修刹车盘',
        '更换轮榖',
        '更换刹车片',
        '更换前/后轮胎',
        '底盘修理',
        '检修变速箱',
        '更换机油',
        '更换机滤',
        '更换空调滤',
        '更换火花塞',
        '更换防冻液',
        '其他',
      ], // 维保项目枚举
      options1: [],//维保类型
      maintenanceForm: [
        {
          keyName: 'spend',
          label: '实际维保费用（元）',
        },
        {
          keyName: 'realTime',
          label: '维保日期',
        },
        {
          keyName: 'realKilometre',
          label: '维保时公里数（km）',
        },
        {
          slot: true,
          keyName: 'fileInfoVOS',
          label: '附件',
          span: 24,
        },
      ],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  watch: {
    'form.other'(e) {
      if (this.form.others) {
        this.form.others = e
      } else {
        this.$set(this.form, 'others', e)
      }
    },
    'form.others'(e) {
      if (this.form.other) {
        this.form.other = e
      } else {
        this.$set(this.form, 'other', e)
      }
    },
  },
  async mounted() {
    this.$route.meta.title = ['车辆维保查看', '车辆维保编辑', '车辆维保申请'][this.editModel]
    this.getMaintenanceType();
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      carMaintenanceApplication
        .detail({ id: this.id })
        .then((res) => {
          this.loading[0] = false
          if (res.data) {
            // 格式化维保项目
            if (res.data.protectProject && this.editModel != 0) {
              res.data.protectProject = res.data.protectProject.split(',') || []
            }
            // 映射车辆信息
            if (Object.keys(res.data.carInfo)?.length > 0) {
              // 映射申请i单位
              res.data.unitName = res.data.carInfo.unitName
              // 映射车牌
              res.data.carNumber = res.data.carInfo.carNumber
              // 映射车辆型号
              res.data.brand = res.data.carInfo.brand
              // 映射司机组织code
              res.data.level = res.data.carInfo.level
            }
            if (res.data.types && res.data.types.length) {
              res.data.maintenanceTypes = [];
              let names = [];
              res.data.types.forEach((item) => {
                res.data.maintenanceTypes.push(item.id);
                names.push(item.name);
              })
              res.data.maintenanceTypeName = names.join(',');
            } else {
              res.data.maintenanceTypes = [];
              res.data.maintenanceTypeName = ''
            }
            this.form = res.data
            this.statusCode = res.data.status // 审批状态
          }
        })
        .catch(() => {
          this.loading[0] = false
        })
    } else {
      const post = this.$currentPost()
      const user = this.$userInfo()
      // 初始化单位
      this.$set(this.form, 'unitName', (post.code === 'PD' ? post.orgName + '-' : '') + post.name)
      this.$set(this.form, 'unitId', post.id)
      // 初始化用户信息
      this.$set(this.form, 'driverName', user.name)
      this.loading[0] = true
      carInfo
        .getAllList({
          driverId: user.id,
        })
        .then((res) => {
          this.loading[0] = false
          if (res.data?.[0]) {
            this.$set(this.form, 'carNumber', res.data[0].carNumber)
            this.$set(this.form, 'brand', res.data[0].brand)
            this.$set(this.form, 'level', res.data[0].level)
            this.form.carId = res.data[0].id
          }
        })
        .catch(() => {
          this.loading[0] = false
        })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('use_car_maintenance_application')
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'unitName',
          type: 'BaseInput',
          disabled: true,
          label: '申请单位',
        },
        {
          keyName: 'driverName',
          type: 'BaseInput',
          disabled: true,
          label: '申请人',
        },
        {
          keyName: 'carNumber',
          type: 'BaseInput',
          disabled: true,
          label: '车牌号',
        },
        {
          keyName: 'brand',
          type: 'BaseInput',
          disabled: true,
          label: '车辆型号',
        },
        {
          keyName: 'preKilometre',
          type: 'BaseInputNumber',
          label: '维保公里数（km）',
          precision: 2,
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'maintenanceTypes',
          label: '维保类型',
          slot: true,
          span: 8,
        },
        {
          keyName: 'protectProject',
          label: '维保项目',
          slot: true,
          span: 24,
        },
        {
          keyName: 'other',
          hidden: !this.form.protectProject?.includes('其他'),
          type: 'BaseTextarea',
          label: '其他',
          span: 24,
          attrs: {
            maxLength: 500,
          },
        },
        {
          keyName: 'others',
          hidden: this.form.protectProject?.includes('其他'),
          type: 'BaseTextarea',
          label: '其他',
          span: 24,
          attrs: {
            maxLength: 500,
          },
        },
        {
          keyName: 'budget',
          type: 'BaseInputNumber',
          label: '预计总费用（元）',
          precision: 2,
          attrs: {
            min: 0
          }
        },
      ]
    },
  },
  methods: {
    getLoadedState(val) {
      this.printLoading = val;
    },
    checkProjectRiskReturnPrint(id) {
      return () => {
        return carMaintenanceApplication.print({ id: id }).then((res) => {
          return res.data.content
        })
      }
    },
    getMaintenanceType() {
      getDataDict({ type: '23' })
        .then((res) => {
          if (res.code === '0') {
            if (res.data && res.data.length) {
              let arr = [];
              res.data.forEach((item) => {
                arr.push({
                  label: item.name,
                  value: item.id
                })
              })
              this.options1 = arr;
            }
          } else {
            this.$message.warning(res.msg || '获取数据失败')
          }
        })
        .catch(() => { })
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      that.setProcessConfig = null;
      //保存草稿、提交，车牌号为空时阻断提交
      if (!this.form.carNumber || this.form.carNumber === null) {
        this.$message.warning('车牌号不能为空')
        return;
      }
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e || statusCode === 0) {
          let name = ['update', 'create'][that.editModel - 1] // 根据操作切换url地址
          statusCode === 0 && that.$refs.ruleForm.clearValidate()
          // 提交表单
          let form = that.$clone(that.form)
          form.status =
            (that.statusCode == '3' && statusCode == 0) || (that.statusCode == '2' && statusCode == 1)
              ? that.statusCode
              : statusCode
          // 格式化用车人员参数
          if (form.protectProject?.length > 0) {
            form.protectProject = form.protectProject?.join()
          } else {
            form.protectProject = ''
          }
          if (form.maintenanceTypes && form.maintenanceTypes.length) {
            let arr = [];
            form.maintenanceTypes.forEach((item) => {
              arr.push({
                id: item
              })
            })
            form.types = arr;
          } else {
            form.types = [];
          }
          that.loading[statusCode] = true
          carMaintenanceApplication[name](form)
            .then((res) => {
              that.loading[statusCode] = false
              that.$message.success(['保存', '提交'][statusCode] + '成功！')
              if (statusCode == 1) {
                //提交时，返回id
                that.businessId = res.data.id;
                that.setProcessConfig = that.processConfig;
                return
              } else {
                that.$multiTab.close()
              }
            })
            .catch(() => {
              // that.$message.warning(['保存', '提交'][statusCode] + '失败！')
              that.loading[statusCode] = false
            })
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-form-item label {
  margin-top: 8px;
}

/deep/.ant-form-item {
  .ant-form-item-label {
    height: 28px;
    width: 180px;
    line-height: 22px;
    padding: 6px 4px 0 0;
    text-align: right;
    white-space: pre-wrap;
    overflow: visible;
  }

  .ant-form-item-control-wrapper {
    width: calc(100% - 180px);
  }
}
</style>
